package com.lawyer.service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ReadContext;
import com.lawyer.config.WeiPayBean;
import com.lawyer.entity.OrderInfo;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.ScheduledUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;

@Service
public class OrderInfoService {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private WeiPayBean weiPayBean;

	
	
	/**
	 * @param orderId
	 * @param userId
	 * @param total
	 *            二维护码支付
	 * 
	 */
	public String wxCreateOrderQrCode(OrderInfo info) {
		String prepayId = "";
		CloseableHttpClient httpClient = buildHttpClient();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			ObjectNode rootNode = objectMapper.createObjectNode();
			
			HttpPost httpPost = new HttpPost(weiPayBean.getNativeUrl());
			httpPost.addHeader("Accept", "application/json");
			httpPost.addHeader("Content-type", "application/json; charset=utf-8");
	
			rootNode.put("mchid", weiPayBean.getMchid())
					.put("appid", weiPayBean.getAppId())
					.put("description", "语音咨询套餐购买")
					.put("notify_url",weiPayBean.getNotifyUrl())
					.put("out_trade_no", info.getId());
			rootNode.putObject("amount").put("total", info.getTotal());
			
			objectMapper.writeValue(bos, rootNode);
			httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
			CloseableHttpResponse response = httpClient.execute(httpPost);

			String result = EntityUtils.toString(response.getEntity());
			logger.info("订单创建返 回结果" + result);
			
			ReadContext ctx = JsonPath.parse(result);
			prepayId = ctx.read("$.code_url");
			logger.info("prepayId===" + prepayId+"--------orderId=====" + info.getUserId());
		} catch (Exception e) {

		} finally {
			try {
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return prepayId;
	}
	
	
	
	
	
	/**
	 * @param orderId
	 * @param userId
	 * @param total
	 *            订单总金额，单位为分
	 * 
	 */
	public String wxCreateOrder(OrderInfo info) {
		String prepayId = "";
		CloseableHttpClient httpClient = buildHttpClient();
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			ObjectNode rootNode = objectMapper.createObjectNode();
			
			HttpPost httpPost = new HttpPost(weiPayBean.getJsapiUrl());
			httpPost.addHeader("Accept", "application/json");
			httpPost.addHeader("Content-type", "application/json; charset=utf-8");
	
			rootNode.put("mchid", weiPayBean.getMchid())
					.put("appid", weiPayBean.getAppId())
					.put("description", "语音咨询套餐购买")
					.put("notify_url", weiPayBean.getNotifyUrl())
					.put("out_trade_no", info.getId());
			rootNode.putObject("amount").put("total", info.getTotal());
			rootNode.putObject("payer").put("openid", info.getUserId());
			
			objectMapper.writeValue(bos, rootNode);
			httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
			CloseableHttpResponse response = httpClient.execute(httpPost);

			String result = EntityUtils.toString(response.getEntity());
			logger.info("订单创建返 回结果" + result);
			
			ReadContext ctx = JsonPath.parse(result);
			prepayId = ctx.read("$.prepay_id");
			logger.info("prepayId===" + prepayId+"--------orderId=====" + info.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return prepayId;
	}

	public CloseableHttpClient buildHttpClient() {
		CloseableHttpClient httpClient = null;
		try {
			Resource privateKey = new DefaultResourceLoader().getResource("classpath:template/apiclient_key.pem");
			PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(privateKey.getInputStream());
			// 使用定时更新的签名验证器，不需要传入证书
			ScheduledUpdateCertificatesVerifier verifier = new ScheduledUpdateCertificatesVerifier(new WechatPay2Credentials(weiPayBean.getMchid(), new PrivateKeySigner(
					weiPayBean.getMchSerialNo(), merchantPrivateKey)), weiPayBean.getApiV3Key().getBytes(StandardCharsets.UTF_8));
			httpClient = WechatPayHttpClientBuilder.create().withMerchant(weiPayBean.getMchid(), weiPayBean.getMchSerialNo(), merchantPrivateKey)
					.withValidator(new WechatPay2Validator(verifier)).build();
		} catch (Exception e) {
			// TODO: handle exception
		}

		return httpClient;

	}
}
